package com.xyc.wemedia.user.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;

public class MyRealm extends AuthorizingRealm {
    /**
     * 授权
     * 权限校验
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //要从数据库中查询当前登录用户的权限。
        String username = principalCollection.getPrimaryPrincipal().toString();
        //通过Username查询数据库中对应的权限信息

        List<String> permissionList = new ArrayList<>();
        permissionList.add("商家列表");
        permissionList.add("商家新增");
        permissionList.add("商品新增");
        permissionList.add("商品列表");
        permissionList.add("商品删除");
        permissionList.add("商品上架");
        permissionList.add("修改密码");

        ArrayList<String> roleList = new ArrayList<>();
        roleList.add("admin");

       /* SecurityUtils.getSubject().getSession().setAttribute("role","admin");*/


        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //将当前用户所拥有的权限交给了Shiro
        simpleAuthorizationInfo.addStringPermissions(permissionList);
        //将查询出来的角色交给当前shiro
        simpleAuthorizationInfo.addRoles(roleList);

        return simpleAuthorizationInfo;
    }

    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //登录业务逻辑
        //UsernamePasswordToken是用户输入的用户名和密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();


        //将角色信息放到Session中
        SecurityUtils.getSubject().getSession().setAttribute("role","admin");

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("root","123456","MyRealm");

        return simpleAuthenticationInfo;
    }
}
